<template>
	<div class="table-demo-container layout-padding">
		<div class="table-demo-padding layout-padding-view layout-padding-auto">
			<TableSearch :search="state.tableData.search" @search="onSearch" @count="onCount" @download="onDownload" />
			<Table ref="tableRef" v-bind="state.tableData" class="table-demo" @pageChange="onTablePageChange"
				@sortHeader="onSortHeader" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import table2excel from 'js-table2excel';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useAttendDailyPageApi, useAttendDailyCountApi, useAttendDailyExportApi } from '/@/api/attend/daily';

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/views/attend/daily/search.vue'));
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);

// 定义变量内容
const tableRef = ref<RefType>();
const state = reactive<TableDemoState>({
	tableData: {
		// 列表数据（必传）
		data: [],
		// 表头内容（必传，注意格式）
		header: [
			{ key: 'employeeCode', colWidth: '', title: '工号', type: 'text', isCheck: true, sortable: true },
			{ key: 'employeeName', colWidth: '', title: '姓名', type: 'text', isCheck: true, sortable: true },
			{ key: 'signIn', colWidth: '', title: '签到时间', type: 'text', isCheck: true, sortable: true },
			{ key: 'signOut', colWidth: '', title: '签退时间', type: 'text', isCheck: true, sortable: true },
			{ key: 'workOnTotal', colWidth: '', title: '工作时长（分钟）', type: 'text', isCheck: true, sortable: true },
			{ key: 'workOverTotal', colWidth: '', title: '加班时长（分钟）', type: 'text', isCheck: true, sortable: true },
			{ key: 'lateArriveTotal', colWidth: '', title: '迟到（分钟）', type: 'text', isCheck: true, sortable: true },
			{ key: 'leaveEarlyTotal', colWidth: '', title: '早退（分钟）', type: 'text', isCheck: true, sortable: true },
			{
				key: 'lossSignIn', colWidth: '', title: '是否迟到', type: 'text', isCheck: true, sortable: true, 
			},
			{
				key: 'lossSignOut', colWidth: '', title: '是否早退', type: 'text', isCheck: true, sortable: true, 
			},
			{
				key: 'lossWork', colWidth: '', title: '是否旷工', type: 'text', isCheck: true, sortable: true, 
			},
			{
				key: 'status', colWidth: '', title: '考勤状态', type: 'text', isCheck: true, sortable: true, 
			},
		],
		// 配置项（必传）
		config: {
			total: 0, // 列表总数
			loading: true, // loading 加载
			isBorder: true, // 是否显示表格边框
			isSerialNo: false, // 是否显示表格序号
			isSelection: false, // 是否显示表格多选
			isOperate: false, // 是否显示表格操作栏
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
		search: [
			{ label: '工号', prop: 'employeeCode', placeholder: '请输入工号', required: false, type: 'input', defaultValue: '' },
			{ label: '姓名', prop: 'employeeName', placeholder: '请输入姓名', required: false, type: 'input', defaultValue: '' },
			{ label: '是否异常', prop: 'status', options: [{ value: 0, label: '全部' }, { value: 1, label: '异常' }, { value: 2, label: '正常' }], placeholder: '请选择考勤状态', required: false, type: 'select', defaultValue: 0 },
			{ label: '是否迟到', prop: 'lossSignIn', options: [{ value: 0, label: '全部' }, { value: 1, label: '迟到' }, { value: 2, label: '正常' }], placeholder: '请选择考勤状态', required: false, type: 'select', defaultValue: 0 },
			{ label: '是否早退', prop: 'lossSignOut', options: [{ value: 0, label: '全部' }, { value: 1, label: '早退' }, { value: 2, label: '正常' }], placeholder: '请选择考勤状态', required: false, type: 'select', defaultValue: 0 },
			{ label: '是否旷工', prop: 'lossWork', options: [{ value: 0, label: '全部' }, { value: 1, label: '旷工' }, { value: 2, label: '正常' }], placeholder: '请选择考勤状态', required: false, type: 'select', defaultValue: 0 },
			{ label: '起始日期', prop: 'startDate', placeholder: '请选择开始日期', required: false, type: 'stamp', defaultValue: moment().add(1000 * 3600 * 24 * -31).format('YYYY-MM-DD') },
			{ label: '结束日期', prop: 'endDate', placeholder: '请选择结束日期', required: false, type: 'stamp', defaultValue: moment().format('YYYY-MM-DD') },
		],
		// 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
		param: {
			pageNum: 1,
			pageSize: 10,
		},
		// 打印标题
		printName: '打印示例',
		downloadList: [] as any
	},
});
// 初始化列表数据
const getTableData = () => {
	state.tableData.config.loading = true;
	state.tableData.data = [];
	useAttendDailyPageApi(state.tableData.param).then(({ content }) => {
		state.tableData.data = content.list.map((item: any) => {
			return {
				...item,
				lossSignIn: item.lossSignIn === 1 ? '是' : '否',
				lossSignOut: item.lossSignOut === 1 ? '是' : '否',
				lossWork: item.lossWork === 1 ? '旷工' : '正常',
				status: item.status === 1 ? '异常' : '正常',
			}
		}) || []
		state.tableData.param.pageSize = content.pageSize
		state.tableData.param.pageNum = content.pageNum
		state.tableData.config.total = content.total
	})
	// 数据总数（模拟，真实从接口取）
	state.tableData.config.loading = false;
};

// 统计数据
const getCountData = () => {
	ElMessageBox.confirm(`统计操作将持续过长时间，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		useAttendDailyCountApi(state.tableData.param).then(() => {
			ElMessage.success('操作成功')
		})
	});
};

// 导出明细
const getDownloadData = () => {
	ElMessageBox.confirm(`此操作将导出考勤明细，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		useAttendDailyExportApi(state.tableData.param).then(({ content }) => {
			state.tableData.config.loading = false;
			state.tableData.downloadList = content.map((item: any) => {
				return {
					...item,
					lossSignIn: item.lossSignIn === 2 ? '否' : '是',
					lossSignOut: item.lossSignOut === 2 ? '否' : '是',
					lossWork: item.lossWork === 2 ? '正常' : '旷工',
					status: item.status === 2 ? '正常' : '异常',
				}
			})
			table2excel(state.tableData.header, state.tableData.downloadList, `${themeConfig.value.globalTitle} ${new Date().toLocaleString()}`);
			ElMessage.success('操作成功')
		})
	});
};

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
	state.tableData.param = Object.assign({}, state.tableData.param, { ...data });
	// tableRef.value.pageReset();
	getTableData()
};

// 搜索点击时表单回调
const onCount = (data: EmptyObjectType) => {
	state.tableData.param = Object.assign({}, { startDate: data.startDate, endDate: data.endDate });
	getCountData()
};
// 搜索点击时表单回调
const onDownload = (data: EmptyObjectType) => {
	state.tableData.param = Object.assign({}, state.tableData.param, { ...data });
	getDownloadData()
};

// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
	state.tableData.param.pageNum = page.pageNum;
	state.tableData.param.pageSize = page.pageSize;
	getTableData();
};
// 拖动显示列排序回调
const onSortHeader = (data: TableHeaderType[]) => {
	state.tableData.header = data;
};
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>

<style scoped lang="scss">
.table-demo-container {
	.table-demo-padding {
		padding: 15px;

		.table-demo {
			flex: 1;
			overflow: hidden;
		}
	}
}

.menu-left {
	height: 650px;
	margin-right: 15px;
	overflow-y: auto;
	padding: 0 5px 30px 0;
	min-width: 300px;
}</style>
